#-IMPORTS----------------------------------------------------------------------
import os
import sys
import conf
from optparse import OptionParser
#-CONSTANTS--------------------------------------------------------------------
ENV_RYCE_CMDLINE = 'RYCE'
DEFAULT_EXT_DIR = 'extensions'
RYCE_CL = 'command-line'
options = ''
op_options = []
#-FUNCTIONS--------------------------------------------------------------------
def __checkOrder(option, opt_str, value, parser):
    """Does order checking on the command-line options.
    """
    if parser.values.op:
        print "ERROR: Can not use %s after -o"%opt_str
        sys.exit(-1)
    if value is None:
        setattr(parser.values, option.dest, True)
    elif value:
        setattr(parser.values, option.dest, False)
    else:
        setattr(parser.values, option.dest, value)

def __getOpParams(p_argv):
    """Strip off the parameters for the specified operation.
    """
    #Convert to string
    temp_argv = ''.join(['%s '%k for k in p_argv])
    n_argv = []
    n_op_argv = []
    #Strip off operation parameters
    t_list = temp_argv.split('(')
    n_argv = t_list[0]
    if len(t_list) > 1:
        n_op_argv = t_list[1]
        n_op_argv = n_op_argv.split(')')[0]
        n_op_argv = n_op_argv.split(' ')
    #Convert first part of the command-line back to a list
    n_argv = n_argv.split(' ')
    #Convert operation command-line to a string
    t_string = ''
    for str in n_op_argv:
        t_string += '%s '%str
    return n_argv, t_string

def loadConfFile(p_cl_list):
    """Takes a list from ConfigParser.read() method and loads RyCE internal
    options structure with values from it.
    """
    for item in p_cl_list:
        name = item[0]
        value = item[1]
        if name == 'force':
            options.force = value
        elif name == 'exclude-ips':
            options.xip = value
        elif name == 'verbose':
            options.verbose = value
        elif name == 'application-name':
            options.appName = value
        elif name == 'exclude-ips':
            options.xip = value
        elif name == 'data-dir':
            options.dataPath = value
        elif name == 'logs-dir':
            options.logsDir = value
        elif name == 'extensions-dir':
            options.extsDir = value
        elif name == 'cluster-name':
            options.cluster = value
        elif name == 'ip-addresses':
            options.ip = value
        elif name == 'operation':
            options.op = value
        elif name == 'remote-user':
            options.user = value
        elif name == 'machine-only':
            options.machine = value
        elif name == 'sequential':
            options.sequential = value
        elif name == 'timeout':
            options.timeout = value
        elif name == 'wait':
            options.wait = value
        elif name == 'threaded':
            options.threaded = value

def setup(argv):
    """Sets up the options for the command-line.
    """
    global op_options
    if len(argv) > 1:
        read_conf_file = False
    else:
        read_conf_file = True
    (argv, op_options) = __getOpParams(argv)
    __parser = OptionParser()
    __parser.add_option('-d', '--data', action='callback', type='string',
                         callback=__checkOrder,
                         dest='dataPath',
                         default='%s%ssysconf.xml'%(os.getcwd(), os.sep),
                         help='Path only of the "sysconf" file.',
                         metavar='PATH')
    __parser.add_option('-e', '--exts', action='callback', type='string',
                         callback=__checkOrder,
                         dest='extsDir',
                         default='%s%sextensions'%(os.getcwd(),
                                                   os.sep),
                         help='The directory where the exentsion(s) are located.',
                         metavar='DIR')
    __parser.add_option('-l', '--log', action='callback', type='string',
                         callback=__checkOrder,
                         dest='logsDir', default='%svar%slog%sryce'%(os.sep,
                                                                     os.sep,
                                                                     os.sep),
                         help='The directory to place the log file(s).',
                         metavar='DIR')
    __parser.add_option('-f', '--force', action='callback',
                         callback=__checkOrder,
                         dest='force', default=False,
                         help='Toggle command-line confirmation.')
    __parser.add_option('-c', '--cluster', action='callback', type='string',
                         callback=__checkOrder,
                         dest='cluster', default='',
                         help='The cluster to issue commands to.',
                         metavar='NAME')
    __parser.add_option('-i', '--ip', action='callback', type='string',
                         callback=__checkOrder,
                         dest='ip', default='',
                         help='The ip(s) address to operate on.  Multiple ips can be separated by a comma (,).',
                         metavar='IP')
    __parser.add_option('-x', '--exclude', action='callback', type='string',
                         callback=__checkOrder,
                         dest='xip', default='',
                         help='Do NOT issue commands to these ip(s). Exclude them.',
                         metavar='IP(s) separated by commas.')
    __parser.add_option('-a', '--apps', action='callback', type='string',
                         callback=__checkOrder,
                         dest='appName', default='',
                         help='The application(s) to operate on.',
                         metavar='NAME')
    __parser.add_option('-u', '--user', action='callback', type='string',
                         callback=__checkOrder,
                         dest='user', default='root',
                         help='Remote host username.',
                         metavar='USER')
    __parser.add_option('-s', '--sequential', action='callback',
                         callback=__checkOrder,
                         dest='sequential', default=False,
                         help='Process commands in a sequential manner.')
    __parser.add_option('-t', '--timeout', action='callback', type='string',
                         callback=__checkOrder,
                         dest='timeout', default=2,
                         help='Time to wait until stopping the operation(s) in seconds.',
                         metavar='SEC')
    __parser.add_option('-w', '--wait', action='callback', type='string',
                         callback=__checkOrder,
                         dest='wait', default=0,
                         help='Time to wait in-between sequential operations in seconds.',
                         metavar='SEC')
    __parser.add_option('-m', '--machine', action='callback',
                         callback=__checkOrder,
                         dest='machine', default=False,
                         help='Forcibly issue command only once per machine.')
    __parser.add_option('-v', '--verbose', action='callback',
                         callback=__checkOrder,
                         dest='verbose', default=False,
                         help='Be verbose in output.')
    __parser.add_option('-k', '--commands', action='callback',
                         callback=__checkOrder,
                         dest='known', default=False,
                         help='List the known command operations.')
    __parser.add_option('-q', '--quiet', action='callback',
                         callback=__checkOrder,
                         dest='verbose', default=False,
                         help='Be totally quiet in output.')
    __parser.add_option('', '--list', action='callback', type='string',
                         callback=__checkOrder,
                         dest='list', default='',
                         help='List information of the specified cluster.',
                         metavar='CLUSTER_NAME')
    __parser.add_option('', '--listall', action='callback',
                         callback=__checkOrder,
                         dest='listall', default=False,
                         help='List all cluster information.')
    __parser.add_option('', '--threaded', action='callback',
                         callback=__checkOrder,
                         dest='threaded', default=False,
                         help='Use the threading engine instead of the process engine.')
    __parser.add_option('', '--version', action='callback',
                         callback=__checkOrder,
                         dest='version', default=False,
                         help='Show the version number.')
    __parser.add_option('', '--conffile', action='callback',
                         callback=__checkOrder,
                         dest='conffile', default=False)
    __parser.add_option('-o', '--op', action='store', type='string',
                         dest='op', default='',
                         help='The operations to perform.  This ends the parameters that RyCE will parse.  What follows enclosed in () will be passed to the operation.',
                         metavar='OP [()]')

    envCmdline = os.getenv(ENV_RYCE_CMDLINE)
    if envCmdline is not None:
        cmdLine = argv + envCmdline.split(' ')
    else:
        cmdLine = argv
    global options
    (options, args) = __parser.parse_args(cmdLine)
    if read_conf_file:
        __config = conf.Conf()
        if __config.isfile:
            __cl_list = __config.config.items(RYCE_CL)
            loadConfFile(__cl_list)
            options.conffile = True

def getOptionsString():
    global options
    result = '-\n'
    result += 'KEY: data (directory)    VALUE: %s\n' % options.dataPath
    result += 'KEY: logs (directory)    VALUE: %s\n'%options.logsDir
    result += 'KEY: extensions (dir)    VALUE: %s\n'%options.extsDir
    result += 'KEY: cluster name        VALUE: %s\n'%options.cluster
    result += 'KEY: application(s) name VALUE: %s\n'%options.appName
    result += 'KEY: ip address(es)      VALUE: %s\n'%options.ip
    result += 'KEY: operation           VALUE: %s\n'%options.op
    result += 'KEY: remote user         VALUE: %s\n'%options.user
    result += 'KEY: exclude ip(s)       VALUE: %s\n'%options.xip
    result += 'KEY: force               VALUE: %s\n'%options.force
    result += 'KEY: machine only        VALUE: %s\n'%options.machine
    result += 'KEY: sequential          VALUE: %s\n'%options.sequential
    result += 'KEY: timeout (seconds)   VALUE: %s\n'%options.timeout
    result += 'KEY: wait (seconds)      VALUE: %s\n'%options.wait
    result += 'KEY: threaded engine     VALUE: %s\n'%options.threaded
    result += 'KEY: verbose             VALUE: %s\n'%options.verbose
    result += 'KEY: config file         VALUE: %s'%options.conffile
    return result
